package top.tenebrous.yzl.im.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import top.tenebrous.yzl.im.ImChatProcessor;
import top.tenebrous.yzl.im.contants.CommonConstants;
import top.tenebrous.yzl.im.context.ImContext;
import top.tenebrous.yzl.im.entity.ImWebSocketProperties;
import top.tenebrous.yzl.im.enums.ChatType;
import top.tenebrous.yzl.im.enums.MessageType;
import top.tenebrous.yzl.im.factory.message.MessageFactory;
import top.tenebrous.yzl.im.message.MessageBody;
import top.tenebrous.yzl.im.message.MessageChatList;
import top.tenebrous.yzl.im.message.MessageNotice;
import top.tenebrous.yzl.im.message.MessageSystemNotice;
import top.tenebrous.yzl.im.model.ImClientChatInfoBean;
import top.tenebrous.yzl.im.model.ImClientFriendsBean;
import top.tenebrous.yzl.im.model.ImClientGroupBean;
import top.tenebrous.yzl.im.model.ImClientUserBean;
import top.tenebrous.yzl.im.observer.AbstractChatRecord;
import top.tenebrous.yzl.im.utils.DateUtils;
import top.tenebrous.yzl.im.utils.WebSocketUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * websocket推送系统消息处理器
 *
 * @author yazhang6
 */
@Slf4j
@Component
public class WebSocketSystemNoticeMessageHandler implements MessageHandler<MessageBody>, InitializingBean {

    @Resource
    private MessageFactory messageFactory;

    @Resource
    private ImWebSocketProperties webSocketProperties;

    @Resource
    private AbstractChatRecord<MessageNotice> chatRecord;

    @Resource
    private ImContext imContext;

    @Resource
    private ImChatProcessor imChatProcessor;

    @SneakyThrows
    @Override
    public void execute(WebSocketSession session, MessageBody message) {
        log.info("{} 推送系统消息开始:接收人id:{}", CommonConstants.LOG_PREFIX, message.getTo());

        // 私聊
        if (ChatType.PRIVATE_CHAT_TYPE.getCode().equals(message.getChatType())) {
            // 获取好友信息
            ImClientFriendsBean friendsBean = imChatProcessor.takeChatFriendInfo(message.getTo(), message.getFrom());
            if (friendsBean == null) {
                log.error("{} 推送系统消息失败:接收人id:{} 不存在", CommonConstants.LOG_PREFIX, message.getTo());
                return;
            }

            List<String> userIds = new ArrayList<String>(){{
                add(message.getTo());
                add(message.getFrom());
            }};
            for (String userId : userIds) {
                WebSocketSession friendSession = WebSocketUtils.getSession(userId);
                MessageSystemNotice messageSystemNotice = new MessageSystemNotice();
                messageSystemNotice.setChatId(userId);
                messageSystemNotice.setChatType(message.getChatType());
                messageSystemNotice.setSystemNotice(message.getContent());
                messageSystemNotice.setUniqueId(friendsBean.getUniqueId());
                WebSocketUtils.send(friendSession, getType(), messageSystemNotice);
                log.info("{} 推送系统消息完成:群组:{} 接收人id:{}", CommonConstants.LOG_PREFIX, message.getGroupId(), userId);
            }
        }
        // 公聊
        else {
            // 1、获取发送者与群组信息
            ImClientGroupBean groupBean = imChatProcessor.takeChatGroupInfo(message.getGroupId(), WebSocketUtils.getUserIdBySession(session));

            // 群组每个在线用户都需要推送
            List<WebSocketSession> sessionGroup = WebSocketUtils.getSessionGroup(message.getGroupId());
            if (CollUtil.isNotEmpty(sessionGroup)) {
                for (WebSocketSession webSocketSession : sessionGroup) {
                    MessageSystemNotice messageSystemNotice = new MessageSystemNotice();
                    messageSystemNotice.setChatId(message.getTo());
                    messageSystemNotice.setChatType(message.getChatType());
                    messageSystemNotice.setSystemNotice(message.getContent());
                    messageSystemNotice.setUniqueId(groupBean.getUniqueId());
                    WebSocketUtils.send(webSocketSession, getType(), messageSystemNotice);
                    log.info("{} 推送系统消息完成:群组:{} 接收人id:{}", CommonConstants.LOG_PREFIX, message.getGroupId(), WebSocketUtils.getUserIdBySession(webSocketSession));
                }
            }


        }

        // 更新群组系统消息字段
        imChatProcessor.updateSystemMessage(message);

        log.info("{} 推送系统消息开始:接收人id:{}", CommonConstants.LOG_PREFIX, message.getTo());
    }

    @Override
    public String getType() {
        return MessageType.SYSTEM.getCode();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        messageFactory.register(MessageType.SYSTEM, this);
    }

}
